package com.onlineauction.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.onlineauction.entities.User;
import com.onlineauction.exceptions.WrongPasswordException;
import com.onlineauction.helpers.Constants;

public class UnsubscribeServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {

		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute(Constants.USERNAME);

		// user not logged in
		if (username == null) {
			response.sendRedirect("/Home");
			return;
		} else {
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/unsubscribe.jsp");
			requestDispatcher.forward(request, response);
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute(Constants.USERNAME);

		// user not logged in
		if (username == null) {
			response.sendRedirect("/Home");
			return;
		} else {
			String password = (String) request.getParameter(Constants.PASSWORD);
			User user = null;
			try {
				user = new User(username, password);
			} catch (WrongPasswordException e) {
				String message = "The password you entered is not correct.";
				request.setAttribute(Constants.MESSAGE, message);
				RequestDispatcher requestDispatcher = request
						.getRequestDispatcher("/unsubscribe.jsp");
				requestDispatcher.forward(request, response);
				return;
			}
			
			user.unsubscribeUser();
			String message = "You have unsubscribed from Online Auction.";
			request.setAttribute(Constants.MESSAGE, message);
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/LogoutAccount");
			requestDispatcher.forward(request, response);
		}
	}

}
